package com.wlstock.funi.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import com.wlstock.funi.model.MyAccountStocks;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.TimeUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class MyAccountStockDao {
	private Dao<MyAccountStocks, Integer> accountDao ;
	private DataBaseHelper helper;
	private static MyAccountStockDao daoInstance;
	
	@SuppressWarnings("unchecked")
	private MyAccountStockDao(Context context){
		try {
			helper = DataBaseHelper.getHelper(context);
			accountDao = helper.getDao(MyAccountStocks.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	public static MyAccountStockDao getInstance(Context mContext){
		if (daoInstance == null) {
			synchronized (MyAccountStockDao.class) {
				if (daoInstance == null) {
					daoInstance = new MyAccountStockDao(mContext);
				}
			}
		}
		return daoInstance;
	}
	

	/**
	 * 查询所有持仓
	 * @return 有效的持仓列表
	 */
	public List<MyAccountStocks> queryAllStocks() {
		List<MyAccountStocks> result = new ArrayList<MyAccountStocks>(); 
		try {
			List<MyAccountStocks> tmpResult = accountDao.queryForAll();
			for (int i = 0; i < tmpResult.size(); i++) {
				MyAccountStocks stock = tmpResult.get(i);
				if (StockUtils.isStkValid(stock.getStkCode())) {
					result.add(stock);
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	
	
	public boolean updateStkQty(String stkCode, int stkQty){
		try {
//			accountDao.updateBuilder().updateColumnValue("stkQty", stkQty).where().eq("stkCode", stkCode);
			accountDao.updateRaw("update MyAccountStocks SET stkQty = ? where stkCode = ? ", new String[]{String.valueOf(stkQty), stkCode});
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	
	
	public boolean updateHighestProRate(String stkCode,float hProfiteRate){
		try {
//			accountDao.updateBuilder().updateColumnValue("hProfiteRate", hProfiteRate).where().eq("stkCode", stkCode);
			accountDao.updateRaw("update MyAccountStocks SET hProfiteRate = ? where stkCode = ? ", new String[]{String.valueOf(hProfiteRate), stkCode});
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean createOrUpdateStock(MyAccountStocks stock){
		try {
			MyAccountStocks tmpResult = accountDao.queryBuilder().where().eq("stkCode", stock.getStkCode()).queryForFirst();
			//防止重新拿回来的时候，hprofitrate这个字段的值又重新变为0存到数据库里面
			if (tmpResult != null) {
				stock.sethProfiteRate(tmpResult.gethProfiteRate());
			}
			accountDao.createOrUpdate(stock);	
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public MyAccountStocks queryStock(String stkCode){
		MyAccountStocks stock = null;
		try {
			stock = accountDao.queryBuilder().where().eq("stkCode", stkCode).queryForFirst();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stock;
	}
	
	/**
	 * 查询所有持仓的股票
	 * @return
	 */
	public ArrayList<MyAccountStocks> queryAccountStocks(){
		ArrayList<MyAccountStocks> myKeepStocks = null;
		try {
			 myKeepStocks = (ArrayList<MyAccountStocks>) accountDao.queryBuilder().query();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return myKeepStocks;
	}
	
	/**
	 * 查询我的持仓所有代码
	 * @return
	 */
	public ArrayList<String[]> queryAccountStockNos() {
		ArrayList<String[]> results = null;
		try {
			GenericRawResults<String[]> rawResults = accountDao.queryRaw("select stkCode from MyAccountStocks");
			results = (ArrayList<String[]>) rawResults.getResults();
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return results;
	}
	
	
	public boolean deleteStock(String stkCode){
		try {
			MyAccountStocks queryStock = queryStock(stkCode);
			if (queryStock != null) {
				accountDao.delete(queryStock);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean deleteAllStocks(){
		try {
			ArrayList<MyAccountStocks> queryAccountStocks = queryAccountStocks();
			if (queryAccountStocks!=null) {
				accountDao.delete(queryAccountStocks);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean deleteInvalidStks(){
		try {
			int rows = accountDao.updateRaw("delete from MyAccountStocks where (stkQty = 0 and serverTradeDate != NULL) or hProfiteRate = 0");
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	 * 这里是更新代挂单的数据库中的数据
	 * 如果持仓原有股票存在目标出售价格，则将原有股票的目标价格拿出来，然后要把数据库中的所有数据删除掉，重新插入
	 * 因为在检测是否要出售的时候是以这个数据库里面的持仓数量作为标准
	 * 每天登录完成之后获取持仓信息都要更新这个
	 * @param stocks
	 * @return
	 */
	public boolean upDateList(List<MyAccountStocks> stocks){
		for (int i = 0 ; i < stocks.size(); i++){
			createOrUpdateStock(stocks.get(i));
		}
		return true;
	}


	/**
	 * 根据代码以及数量查询
	 * @param stkCode
	 * @param qty
     * @return
     */
	public MyAccountStocks queryMyAccountByCodeAndQty(String stkCode, String qty) {
		try {
			return accountDao.queryBuilder().where().eq("stkCode",stkCode).and().eq("stkQty",qty).queryForFirst();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据代码查询
	 * @param stkCode
	 * @return
	 */
	public MyAccountStocks queryMyAccountByCode(String stkCode) {
		try {
			return accountDao.queryBuilder().where().eq("stkCode",stkCode).queryForFirst();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询最后一个时间的交易数据
	 * @return
     */
	public MyAccountStocks queryLastStockDay() {
		try {
			MyAccountStocks stock = accountDao.queryBuilder().orderBy("serverTradeDate", false).queryForFirst();
			return stock;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 查询超过时间的持仓记录
	 * @param  defaultMaxDays 默认最大持仓时间
     */
	public List<MyAccountStocks> queryStocksOutOfMaxDays(int defaultMaxDays) {
		List<MyAccountStocks> resultList = new ArrayList<MyAccountStocks>();
		try {
			List<String[]> results = accountDao.queryRaw("select m.stkCode,m.stkName from MyAccountStocks m where m.keepDaysCount >= m.targetDaysCount or m.keepDaysCount >= ?", String.valueOf(defaultMaxDays)).getResults();
			if (results!=null && !results.isEmpty()){
				for (int i = 0 ; i < results.size(); i++){
					MyAccountStocks myAccountStock = new MyAccountStocks(results.get(i));
					resultList.add(myAccountStock);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultList;
	}

	/**
	 * 查询持仓是否是最新的,默认为最近15分钟
	 * @param date
	 * @param offset
     * @return
     */
	public boolean isMyAccountNewly(Date date, int offset) {
		try {
			MyAccountStocks model = accountDao.queryBuilder().orderBy("lastUpdate", true).queryForFirst();
			if (model!=null && model.getLastUpdate()!=null){
				return TimeUtils.isDateInPeriodRange(model.getLastUpdate(), date, TimeUtils.TIME_PERIOD.MIN, offset);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 查询我的持仓所有股票的总市值
	 * @return
     */
	public float queryMyAccountTotalFund() {
		try {
			String[] result = accountDao.queryRaw("select sum(marketPrice) from MyAccountStocks").getFirstResult();
			if (result!=null && result.length > 0){
				return Float.valueOf(result[0]);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 场景A操盘手买入A股票 第二天卖出，然后账户挂单卖出A股票，第3天B操盘手买入，第四天B操盘手卖出A股票，如果全盘以这种价格挂单卖出
	 * 则跟规则不符，所以持仓挂单卖的股票还要以操盘手的信息作为附带信息
	 * 这个可以后续加入
	 */
}
